import { createJSONStorage } from 'jotai/utils';
import Cookies from 'js-cookie';

/**
 * 创建持久化存储实例 - localStorage + cookie
 * @description localStorage + cookie 存储，方便同时享有 server-side 渲染主题(cookie)和 client-side 监听 storage 事件，同步多tab数据(storage listener)
 */
export function createJSONStorageWithCookies<T>() {
  return createJSONStorage<T>(() => ({
    getItem(key) {
      if (typeof window === 'undefined') return null;
      return localStorage.getItem(key) || Cookies.get(key) || null;
    },
    setItem(key, newValue) {
      if (typeof window === 'undefined') return;
      localStorage.setItem(key, newValue);
      Cookies.set(key, newValue, { expires: 365 });
    },
    removeItem(key) {
      if (typeof window === 'undefined') return;
      localStorage.removeItem(key);
      Cookies.remove(key);
    },
    subscribe(key, callback) {
      if (typeof window === 'undefined') return () => {};
      const handler = (e: StorageEvent) => {
        if (e.key === key && e.newValue) {
          callback(e.newValue);
        }
      };
      // 监听 storage 变化, 同步多个tab之间的数据
      window.addEventListener('storage', handler);
      return () => window.removeEventListener('storage', handler);
    },
  }));
}
